package com.ehotting.eaf.spring.cloud.service;

import com.alibaba.cloud.nacos.NacosConfigManager;
import com.alibaba.cloud.nacos.NacosConfigProperties;
import com.alibaba.nacos.api.config.ConfigType;
import com.alibaba.nacos.api.exception.NacosException;
import com.ehotting.eaf.core.utils.AssertUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import org.yaml.snakeyaml.Yaml;

@Component
@Slf4j
public class NacosConfigService {

    @Autowired
    private NacosConfigProperties nacosConfigProperties;
    @Autowired
    private NacosConfigManager nacosConfigManager;
    @Autowired
    private Environment env;

    public String get(String preName) {
        // 设置需要同步的配置信息
        String fileName =preName +"-"+env.getActiveProfiles()[0]+ "."+nacosConfigProperties.getFileExtension();
        String group = nacosConfigProperties.getGroup();
        try {
            String content = nacosConfigManager.getConfigService().getConfig(fileName,
                    group,5000L);
            log.info(content);
            return content;
        } catch (NacosException e) {
            e.printStackTrace();
        }
        return null;
    }


    public void save(String preName,String content) {
        AssertUtils.hasText(content,"Arguments[context] is null");
        Object data = new Yaml().load(content);
        AssertUtils.notNull(data,"Arguments[content] yaml format error");
        String fileName =preName +"-"+env.getActiveProfiles()[0]+ "."+nacosConfigProperties.getFileExtension();
        String group = nacosConfigProperties.getGroup();
        try {
            nacosConfigManager.getConfigService().publishConfig(
                    fileName,
                    group,
                    content, ConfigType.YAML.getType());
        } catch (NacosException e) {
            e.printStackTrace();
        }
    }
}
